package fi.iki.juri.units.generator;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class TranslationParser {
	private static final String LOCALE_XPATH = "locale";
	private static final String UNIT_XPATH = "unit";
	private static final String TRANS_XPATH = "trans";

	private static final String TRANSLATION_ELEMENT = "translation";
	
	private XPathCompiler.ExpressionWrapper localePath;
	private XPathCompiler.ExpressionWrapper unitPath;
	private XPathCompiler.ExpressionWrapper transPath;
	
	public TranslationParser() {
		final XPathCompiler compiler = new XPathCompiler();
		localePath = compiler.compile(LOCALE_XPATH);
		unitPath = compiler.compile(UNIT_XPATH);
		transPath = compiler.compile(TRANS_XPATH);
	}
	
	public ParsedTranslations parse(final InputStream stream) {
		final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		final ParsedTranslations translations;
		try {
			final Document doc = factory.newDocumentBuilder().parse(stream);
			final String locale = localePath.readString(doc.getDocumentElement());
			translations = new ParsedTranslations(locale);
			for (final Element element : new IterableNodeList(doc.getElementsByTagName(TRANSLATION_ELEMENT))) {
				final String unit = unitPath.readString(element);
				final String translation = transPath.readString(element);
				translations.addTranslation(unit, translation);
			}
		} catch (final Exception ex) {
			throw new RuntimeException(ex);
		}
		return translations;
	}
}
